package com.yunyao.web.controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import com.yunyao.common.dto.excel.ContractExcelDto;
import com.yunyao.common.dto.excel.SettlementExcelDto;
import com.yunyao.common.dto.project.HistoryQtDto;
import com.yunyao.common.dto.project.ProjectSettlementDto;
import com.yunyao.common.dto.project.ProjectSettlementMaterialDto;
import com.yunyao.common.dto.project.ProjectSettlementOrderDto;
import com.yunyao.common.dto.supplier.SupplierSettlementMaterialDto;
import com.yunyao.common.web.util.PageResult;
import com.yunyao.common.web.util.YResult;
import com.yunyao.framework.dto.file.FileInfoDto;
import com.yunyao.framework.dto.project.ProjectSettlementApprovalDto;
import com.yunyao.framework.dto.project.ProjectSettlementCheckDto;
import com.yunyao.framework.dto.project.ProjectSettlementConfirmDto;
import com.yunyao.framework.dto.project.ProjectSettlementDeletedDto;
import com.yunyao.framework.dto.project.ProjectSettlementSaveDto;
import com.yunyao.framework.dto.project.ProjectSettlementSubmitApprovalDto;
import com.yunyao.framework.dto.reconciliation.ReconciliationMaterialDto;
import com.yunyao.framework.dto.soSupply.SoSupplyMaterialDto;
import com.yunyao.framework.service.ProjectSettlementService;
import com.yunyao.framework.vo.project.ProjectSettlementInfoVO;
import com.yunyao.framework.vo.project.ProjectSettlementMaterialVO;
import com.yunyao.framework.vo.project.ProjectSettlementOrderVO;
import com.yunyao.framework.vo.project.ProjectSettlementVO;
import com.yunyao.framework.vo.reconciliation.ReconciliationMaterialVO;
import com.yunyao.framework.vo.sosyupply.SoSupplyMaterialVO;
import com.yunyao.web.utils.AliOssUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotBlank;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;

/**
 * @author xingjishuai
 * @date 2024-07-22
 */
@Slf4j
@RestController
@RequestMapping("/projectSettlement")
public class ProjectSettlementController {
    @Autowired
    private ProjectSettlementService projectSettlementService;

    /**
     * 项目结算列表
     *
     * @param projectSettlementDto
     * @return
     */
    @GetMapping("/list")
    public YResult<PageResult<ProjectSettlementVO>> pageList(ProjectSettlementDto projectSettlementDto) {
        return projectSettlementService.pageList(projectSettlementDto);
    }

    /**
     * 项目结算详情
     *
     * @param settlementDto
     * @return
     */
    @GetMapping("/info")
    public YResult<ProjectSettlementInfoVO> getInfo(ProjectSettlementDto settlementDto) {
        return projectSettlementService.getInfo(settlementDto);
    }

    /**
     * 项目结算材料列表
     *
     * @param projectSettlementMaterialDto
     * @return
     */
    @GetMapping("/material/list")
    public YResult<PageResult<ProjectSettlementMaterialVO>> materialPageList(ProjectSettlementMaterialDto projectSettlementMaterialDto) {
        return projectSettlementService.materialPageList(projectSettlementMaterialDto);
    }

    @GetMapping("/reconciliationmaterial/list")
    public YResult<PageResult<ReconciliationMaterialVO>> getContractMaterialList(ReconciliationMaterialDto reconciliationMaterialDto) {
        return projectSettlementService.getReconciliationMaterialListbySupplyId(reconciliationMaterialDto);
    }

    /**
     * 项目结算对账订单列表
     *
     * @param projectSettlementOrderDto
     * @return
     */
    @GetMapping("/order/list")
    public YResult<PageResult<ProjectSettlementOrderVO>> orderPageList(ProjectSettlementOrderDto projectSettlementOrderDto) {
        return projectSettlementService.orderPageList(projectSettlementOrderDto);
    }

    @PostMapping("/getSupplyTaxTotalPrice")
    public YResult<BigDecimal> getSupplyTaxTotalPrice(@RequestBody HistoryQtDto dto) {
        return YResult.success(projectSettlementService.getSupplyTaxTotalPrice(dto));
    }

    /**
     * 项目结算确认
     *
     * @param projectSettlementConfirmDto
     * @return
     */
    @PostMapping("/confirm")
    public YResult<String> confirm(@RequestBody @Validated ProjectSettlementConfirmDto projectSettlementConfirmDto) {
        return projectSettlementService.confirm(projectSettlementConfirmDto);
    }

    /**
     * @param projectSettlementMaterialDto
     * @return
     */
    @GetMapping("/material/count")
    public YResult<Map<String, Object>> materialCount(ProjectSettlementMaterialDto projectSettlementMaterialDto) {
        return projectSettlementService.materialCount(projectSettlementMaterialDto);
    }

    /**
     * 项目云采确认
     *
     * @param projectSettlementConfirmDto
     * @return
     */
    @PostMapping("/yc/confirm")
    public YResult<String> ycConfirm(@RequestBody @Validated ProjectSettlementConfirmDto projectSettlementConfirmDto) {
        return projectSettlementService.ycConfirm(projectSettlementConfirmDto);
    }

    /**
     * 项目结算核对
     *
     * @param projectSettlementCheckDto
     * @return
     */
    @PostMapping("/check")
    public YResult<String> check(@RequestBody @Validated ProjectSettlementCheckDto projectSettlementCheckDto) {
        return projectSettlementService.check(projectSettlementCheckDto);
    }

    /**
     * 项目结算删除
     *
     * @param projectSettlementDeletedDto
     * @return
     */
    @PostMapping("/deleted")
    public YResult<String> deleted(@RequestBody @Validated ProjectSettlementDeletedDto projectSettlementDeletedDto) {
        return projectSettlementService.deleted(projectSettlementDeletedDto);
    }

    /**
     * 项目结算保存
     *
     * @param projectSettlementSaveDto
     * @return
     */
    @PostMapping("/save")
    public YResult<String> save(@RequestBody ProjectSettlementSaveDto projectSettlementSaveDto) {
        return projectSettlementService.save(projectSettlementSaveDto);
    }

    /**
     * 项目结算提交审批
     *
     * @param approvalDto
     * @return
     */
    @PostMapping("/submit/approval")
    public YResult<String> submitApproval(@RequestBody @Validated ProjectSettlementSubmitApprovalDto approvalDto) {
        return projectSettlementService.submitApproval(approvalDto);
    }

    /**
     * 项目结算审批
     *
     * @param approvalDto
     * @return
     */
    @PostMapping("/approval")
    public YResult<String> approval(@RequestBody @Validated ProjectSettlementApprovalDto approvalDto) {
        return projectSettlementService.approval(approvalDto);
    }


    /**
     * 导出文件
     *
     * @return
     */

    @GetMapping("/export/file")
    public YResult<String> exportFile(ProjectSettlementDto projectSettlementDto, HttpServletResponse response) {
        try {
            List<SettlementExcelDto> contractMaterialExportDtoList = projectSettlementService.export(projectSettlementDto);
            try {
                // 这里URLEncoder.encode可以防止中文乱码
                String fileName = URLEncoder.encode("projectSettlement", String.valueOf(StandardCharsets.UTF_8)) + ".xlsx";
//                response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
                //设置sheet名
                ExportParams params = new ExportParams();
                params.setSheetName("结算信息模版");
                //设置标题
//                params.setTitle("商品信息");
                // 这里需要设置不关闭流
                Workbook workbook = ExcelExportUtil.exportExcel(params, SettlementExcelDto.class, contractMaterialExportDtoList);
                //输出流
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                workbook.write(bos);
                byte[] bytes = bos.toByteArray();
                bos.close();
                try {
                    FileInfoDto fileInfoDto = AliOssUtil.upload(bytes,
                            fileName, null);
                    if (null != fileInfoDto) {
                        return YResult.success(fileInfoDto.getLink());
                    } else {
                        return YResult.error("连接文件服务器失败，请重试");
                    }
                } catch (Exception e) {
                    return YResult.error("下载失败，请重试");
                }
            } catch (IOException e) {
                System.out.println(e.getMessage());
            }
        } catch (Exception e) {
            log.error("导出结算信息失败", e);
        }
        return YResult.error("导出结算信息失败");
    }

}
